package com.google.code.twithis.core.transaction;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.Base64OutputStream;

import com.google.code.twithis.core.constants.SystemConstants;

public class TwitterTransaction extends Thread {

	private final String login;

	private final String password;

	private String payload;

	private TransactionListener listener;

	public TwitterTransaction(String login, String password, String payload) {
		this.login = login;
		this.password = password;
		this.payload = payload;
	}

	public TwitterTransaction(String login, String password, String payload, TransactionListener listener) {
		super();
		this.login = login;
		this.password = password;
		this.payload = payload;
		this.listener = listener;
	}

	public void run() {
		String concat = login + ":" + password;

		String authentication = null;
		try {
			authentication = Base64OutputStream.encodeAsString(concat.getBytes(), 0, concat.length(), false, false);
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		HttpConnection conn = null;
		try {
			conn = (HttpConnection) Connector.open(SystemConstants.getUrl(SystemConstants.UPDATE));
			conn.setRequestMethod(HttpConnection.POST);
			conn.setRequestProperty("Authorization", "Basic " + authentication);

			OutputStream out = conn.openOutputStream();
			out.write(("status=" + payload).getBytes());
			out.flush();
			out.close();

			InputStream in = conn.openInputStream();

			int b = -1;

			StringBuffer sb = new StringBuffer();

			while ((b = in.read()) != -1) {
				sb.append((char) b);
			}

			in.close();

			listener.onSuccess(sb.toString());
		}
		catch (IOException e) {
			listener.onFailure(e);
			e.printStackTrace();
		}
		finally {
			try {
				conn.close();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public TransactionListener getListener() {
		return listener;
	}

	public void setListener(TransactionListener listener) {
		this.listener = listener;
	}

}
